package com.bieyang.anjia.net;

import java.util.Map;

import com.bieyang.anjia.refresh.BasicHandler;
import com.bieyang.anjia.viewmodel.UserViewModel;
import com.http.volley.Request;
import com.http.volley.Response.ErrorListener;
import com.http.volley.Response.Listener;
import com.http.volley.VolleyError;

/*************************文件信息*****************************
 * 模块名：AnJia
 * 文件名：NetAliveManager.java 
 * 创建者：刘松
 * 创建日期： 2015年2月10日 
 * 功能描述：
 ***********************************************************/
public class AliveManager {
	static AliveManager manager;

	static final int MAX_ALIVE = 3;

	static final int ALIVE_TIME = 40 * 1000;

	static int FAILD_COUNT = 0;

	boolean HasLogin;

	Thread aliveThread;
	
	UserViewModel viewModel;

	Listener<String> handler;
	ErrorListener faildListener;

	private AliveManager(UserViewModel vmModel) {
		this.viewModel = vmModel;
		handler = new Listener<String>() {
			@Override
			public void onResponse(Request<String> req, String arg1, Map<String, String> headerMap) {
				FAILD_COUNT = 0;
				String cookie = headerMap.get("Set-Cookie");
				if (cookie != null)
					CookieStoreManager.updateCookies(cookie);
			}
		};
		faildListener = new ErrorListener() {
			@Override
			public void onErrorResponse(@SuppressWarnings("rawtypes") Request arg0, VolleyError arg1) {
				FAILD_COUNT++;

				if (FAILD_COUNT >= MAX_ALIVE) {
					// TODO 重新登录逻辑
					viewModel.reLogin();
				}
			}
		};
	}
	
	public static AliveManager getInstance(UserViewModel vmModel){
		if(manager == null)
			manager = new AliveManager(vmModel);
		return manager;
	}

	public void startAlive() {
		HasLogin = true;
		if (aliveThread == null) {
			aliveThread = new Thread(new Runnable() {
				public void run() {
					while (HasLogin) {
						try {
							Thread.sleep(ALIVE_TIME);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						sendAlive();
					}
				}
			});
			aliveThread.start();
		}
	}

	public void stopAlive() {
		HasLogin = false;
		if (aliveThread != null) {
			aliveThread.interrupt();
			aliveThread = null;
		}
	}

	private void sendAlive() {
		NetProccess.getDefault(BasicHandler.application).sendAlive(handler, faildListener);
	}

}
